//
//  NewsstandController.m
//  TouchTest
//
//  Created by fengxijun on 2/19/16.
//  Copyright © 2016 goappbox. All rights reserved.
//

#import "NewsstandController.h"
#import <NewsstandKit/NewsstandKit.h>
#import "SecondController.h"

@interface NewsstandController ()
<
    NSURLConnectionDownloadDelegate
>
{
//    NSMutableArray *finish;
}
@property (nonatomic, strong) CAShapeLayer *loadingLayer;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation NewsstandController

- (void) viewDidLoad
{
    [super viewDidLoad];
//    finish = [[NSMutableArray alloc] init];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(60, 100, 200, 200);
    btn.center = self.view.center;
    [btn setTitle:@"Apple Pay" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(addDownLoad:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
//    [self drawHalfCircle:btn];
    
}

- (CAShapeLayer *)drawCircle:(UIView *)view {
    CAShapeLayer *circleLayer = [CAShapeLayer layer];
    // 指定frame，只是为了设置宽度和高度
    circleLayer.frame = view.bounds;
    // 设置居中显示
    circleLayer.position = CGPointMake(view.frame.size.width / 2.f, view.frame.size.height / 2.f);
    // 设置填充颜色
    circleLayer.fillColor = [UIColor clearColor].CGColor;
    // 设置线宽
    circleLayer.lineWidth = 2.0;
    // 设置线的颜色
    circleLayer.strokeColor = [UIColor redColor].CGColor;
    
    // 使用UIBezierPath创建路径
//    CGRect frame = CGRectMake(0, 0, 200, 200);
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:view.bounds];
    
    // 设置CAShapeLayer与UIBezierPath关联
    circleLayer.path = circlePath.CGPath;
    
    // 将CAShaperLayer放到某个层上显示
    [view.layer addSublayer:circleLayer];
    
    return circleLayer;
}

- (void)drawHalfCircle:(UIView *)view {
    if (self.loadingLayer != nil) {
        [self.loadingLayer removeFromSuperlayer];
    }
    self.loadingLayer = [self drawCircle:view];
    
    // 这个是用于指定画笔的开始与结束点
    self.loadingLayer.strokeStart = 0.0;
    self.loadingLayer.strokeEnd = 0.75;
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                  target:self
                                                selector:@selector(updateCircle)
                                                userInfo:nil
                                                 repeats:YES];
}

- (void)updateCircle {
    if (self.loadingLayer.strokeEnd > 1 && self.loadingLayer.strokeStart < 1) {
        self.loadingLayer.strokeStart += 0.1;
    } else if (self.loadingLayer.strokeStart == 0) {
        self.loadingLayer.strokeEnd += 0.1;
    }
    
    if (self.loadingLayer.strokeEnd == 0) {
        self.loadingLayer.strokeStart = 0;
    }
    
    if (self.loadingLayer.strokeStart >= 1 && self.loadingLayer.strokeEnd >= 1) {
        self.loadingLayer.strokeStart = 0;
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)pushAni
{
    [UIView transitionWithView:self.navigationController.view duration:0.5 options:UIViewAnimationOptionTransitionCurlUp animations:^{
        SecondController *ctrl = [[SecondController alloc] init];
        [self.navigationController pushViewController:ctrl animated:NO];
    } completion:^(BOOL finished) {
        //
    }];
//    SecondController *ctrl = [[SecondController alloc] init];
//    [self.navigationController pushViewController:ctrl animated:NO];
//    CATransition *tran = [CATransition animation];
//    tran.duration = 0.75;
//    tran.type = @"cameraIrisHollowOpen";
//    tran.subtype = kCATransitionFromLeft;
//    [self.navigationController.view.layer addAnimation:tran forKey:nil];
}

- (void)addDownLoad:(UIButton *)btn
{
    [self pushAni];
//    [self drawHalfCircle:btn];
}

- (void) downloadNews:(NSString *)url issueName:(NSString *)name
{
    NSURL *myUrl = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:myUrl cachePolicy:0 timeoutInterval:MAXFLOAT];
    //尝试从NKLibrary单例中取出指定NKIssue对象
    NKIssue *issue = [[NKLibrary sharedLibrary] issueWithName:name];
    if (!issue) {
        //指定NKIssue对象在NKLibrary则创建一个NKIssue对象
        issue = [[NKLibrary sharedLibrary] addIssueWithName:name date:[NSDate date]];
        //设置NKIssue对象的请求对象，并获取NKAssetDownload下载对象
        NKAssetDownload *download = [issue addAssetWithRequest:request];
        [download downloadWithDelegate:self];
    } else {
//        return issue.contentURL;
    }
}

- (void) connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
{
    NKAssetDownload *download = [connection newsstandAssetDownload];
    NSLog(@"第%@个 下载了 百分之%lld",[download.userInfo objectForKey:@"index"],expectedTotalBytes / totalBytesWritten);
}

- (void) connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes
{
    NKAssetDownload *download = [connection newsstandAssetDownload];
    NSLog(@"第%@个 下载了 百分之%lld",[download.userInfo objectForKey:@"index"],expectedTotalBytes / totalBytesWritten);
}

- (void) connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *)destinationURL
{
    NKAssetDownload *download = [connection newsstandAssetDownload];
    NKIssue *issue = download.issue;
    NSString *lastName = [[[destinationURL path] componentsSeparatedByString:@"/"] lastObject];
    [[NSFileManager defaultManager] moveItemAtPath:[destinationURL path] toPath:[issue.contentURL path] error:nil];
    //
    
}

@end
